﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLK.Database;
using Utilities;
using QLK.Web.App_Code;
using QLK.Database.BLLs;

namespace QLK.Web
{
    public partial class SupplierDetails : System.Web.UI.Page
    {
        private string _supplierID;
        protected void Page_Load(object sender, EventArgs e)
        {
            _supplierID = Request.QueryString[Columns.SupplierID];
            if (!IsPostBack)
            {
                if (_supplierID != null && _supplierID != string.Empty)
                {
                    int ID = ConvertHelper.CheckQueryString_Int(_supplierID);
                    if (ID == -1)
                    {
                        //redirect to error page
                    }
                    else
                    {
                        LoadSupplierDetails(ID);
                    }
                }
            }
        }

        private void LoadSupplierDetails(int supplierID)
        {
            SupplierBLL bll = new SupplierBLL();
            Supplier supp;
            supp = bll.GetSupplierBySupplierID(int.Parse(_supplierID));
            txtAddress.Text=Request.QueryString[Columns.Address];
            txtSupplierName.Text=Request.QueryString[Columns.SupplierName];
            txtPhoneNumber.Text=Request.QueryString[Columns.PhoneNumber];
            // gan vao text box
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool res = false;
            SupplierBLL bll = new SupplierBLL();
            Supplier supp;
            if (_supplierID != null && _supplierID != string.Empty)
            {
                supp = bll.GetSupplierBySupplierID(int.Parse(_supplierID));
                supp.SupplierName = txtSupplierName.Text.Trim();
                supp.Address = txtAddress.Text.Trim();
                supp.PhoneNumber = txtPhoneNumber.Text.Trim();
                if(bll.UpdateSupplier(supp))
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "update successfully!";
                    res = true;
                }

            }
            else
            {
                supp = new Supplier();
                supp.SupplierName = txtSupplierName.Text.Trim();
                supp.Address = txtAddress.Text.Trim();
                supp.PhoneNumber = txtPhoneNumber.Text.Trim();
                if (bll.InsertSupplier(supp))
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "insert successfully!";
                    res = true;
                }
            }
            if (res)
                Response.Redirect(PageUrls.SupplierManagement);
            else{
                // loi
            }
        }
    }
}
